#coding: utf-8
import json, sys
sys.path.append("/code/base")
import tool_funcs as util

class Webin():
  def __init__(self, environ):
    if isinstance(environ, bytes):
      environ = environ.decode("utf-8")
      environ = json.loads(environ)
    self.environ = environ
    self.args = self.fetch_args()
    self.util = util
  
  def fetch_args(self):
    # context = self.environ['fc.context']
    # request_uri = self.environ['fc.request_uri']
    for k, v in self.environ.items():
        if k.startswith("HTTP_"):
            # process custom request headers
            pass

    request_method = self.environ['requestContext']['http']['method'].encode('utf-8').lower()
    
    if request_method == 'get':
      return self._querystr_to_dict(self.environ['queryParameters'].encode('utf-8'))
    else:
      request_body = self.environ['body']
      return self._querystr_to_dict(request_body)
    
  def _querystr_to_dict(self, querystr):
    if not querystr: return {}
    d = {}
    try:
      d = json.loads(querystr)
    except:
      for item in querystr.split('&'):
        k, v = item.split('=')
        key = k.encode('utf-8')
        value = v.encode('utf-8')
        d[key.decode('utf-8')] = value.decode('utf-8')
    return d